package com.bwie.utils.poi;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.afterturn.easypoi.util.PoiMergeCellUtil;
import cn.hutool.core.bean.BeanUtil;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @program: smart-parking
 * @ClassName EasyPoiUtil
 * @description:
 * @author: wdd
 * @create: 2024-08-01 22:49
 * @Version 1.0
 **/
@Component
public class EasyPoiUtil {

    /**
     * 导入
     */
    /**
     *
     * @param file：
     * @param pojoClass
     * @return
     * @throws Exception
     */
    public List<?> importFileExcel(MultipartFile file,Class<?> pojoClass) throws Exception {
        InputStream inputStream = file.getInputStream();//文件输入流
        ImportParams params = new ImportParams();//创建一个导入参数对象
        params.setHeadRows(1);//从第几行读取
        List<?> list = ExcelImportUtil.importExcel(inputStream, pojoClass, params);
        return list;
    }


    /**
     * 普通导出
     * @param response
     */
    public void exportExcel(HttpServletResponse response, List<?> list,Class<?> pojoClass,String fileName){
        // 1.导出，并获取工作簿
        Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(null, "简单导出测试表"), pojoClass, list);
        // 2.输出
        responseWorkbook(response, workbook, fileName);

    }



    /**
     * 模板导出
     * @param response；响应
     * @param fileName：文件名
     * @param list：导出内容集合
     * @param templateUrl：模板文件路径
     */
    public void exportTemplateExcel(HttpServletResponse response,String fileName,List<?> list,String templateUrl){

        // 获取模板数据
        //TemplateExportParams params = new TemplateExportParams("D:\\workspace\\2204a\\ssm_001\\src\\main\\resources\\excel\\导出模版.xlsx", 0);
        TemplateExportParams params = new TemplateExportParams(templateUrl, 0);

        ArrayList<Map<String, Object>> list2 = new ArrayList<>();

        /*for (Charge charge2 : list) {
            // 塞入具体数据，工具类用的是 hutool 包
            list2.add(BeanUtil.beanToMap(charge2));
        }*/
        for (Object o : list) {
            list2.add(BeanUtil.beanToMap(o));
        }


        HashMap<String, Object> workbookNeedMap = new HashMap<>();
        workbookNeedMap.put("maps", list2);

        // 导出，并获取工作簿
        Workbook workbook = ExcelExportUtil.exportExcel(params, workbookNeedMap);

        // ================= 结束输出 ==================

        // 输出
        responseWorkbook(response, workbook, fileName);

    }



    /**
     * excel导出-合并单元格
     * list 数据列表
     * title 报表标题
     * sheetName excel工作表名
     * pojoClass 导出实体类
     * fileName 导出excel文件名称
     * response
     * columns 需要进行合并的列
     */
    public void exportMerge(HttpServletResponse response, List<?> list, String title, String sheetName,
                            Class<?> pojoClass, String fileName,Integer[] columns) {
        ExportParams exportParams = new ExportParams(title, sheetName, ExcelType.XSSF);
        //把数据添加到excel表格中
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, pojoClass, list);

        //对单元格进行合并--对第一张工作表第2行第columns列开始合并
        PoiMergeCellUtil.mergeCells(workbook.getSheetAt(0),1,columns);

        // 输出
        responseWorkbook(response, workbook, fileName);
    }

//
//    /**
//     * 多sheet导出
//     * @param response
//     * @param fileName
//     * @param list
//     * @param sheetSize
//     */
//    public void exportManySheetExcel(HttpServletResponse response, String fileName,List<Charge> list,Integer sheetSize){
//
//        //将数据进行按照sheetSize个拆分(拆分数据自己定义)
//        List<List<Charge>> partition = Lists.partition(list, sheetSize);
//        // 多个sheet配置参数
//        List<Map<String, Object>> sheetsList = new ArrayList<>();
//        AtomicInteger atomicInteger = new AtomicInteger();
//        partition.forEach(exportList -> {
//            //将分割的数据赋值
//            List<Charge> chargeExportList = new ArrayList<>();
//            for (Charge order : exportList) {
//                Charge charge = new Charge();
//                BeanUtil.copyProperties(order,charge);
//                chargeExportList.add(charge);
//            }
//            String sheetName = "sheet" + atomicInteger.addAndGet(1);
//            Map<String, Object> exportMap = Maps.newHashMap();
//            ExportParams exportParams = new ExportParams(null, sheetName, ExcelType.HSSF);
//            // 以下3个参数为API中写死的参数名 分别是sheet配置/导出类（注解定义）/数据集
//            exportMap.put("title", exportParams);
//            exportMap.put("entity", Charge.class);
//            exportMap.put("data", chargeExportList);
//            // 加入多sheet配置列表
//            sheetsList.add(exportMap);
//        });
//        Workbook workbook = ExcelExportUtil.exportExcel(sheetsList, ExcelType.HSSF);
//        // 2.输出
//        responseWorkbook(response, workbook, fileName);
//    }

















    private void responseWorkbook(HttpServletResponse response, Workbook workbook, String fileName) {

        try {
            response.setHeader("Content-disposition", "attachment;" + "filename*=utf-8''" + URLEncoder.encode(fileName+".xlsx", "UTF-8"));
            response.setContentType("application/octet-stream; charset=UTF-8");
            workbook.write(response.getOutputStream());
            workbook.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }





}